package com.sunshine.wrongquestionset.activity.main

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.SearchView
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.sunshine.wrongquestionset.R
import com.sunshine.wrongquestionset.callback.OnListEmptyListener
import com.sunshine.wrongquestionset.callback.OnRefreshListener
import com.sunshine.wrongquestionset.room.entity.QuestionEntity
import com.sunshine.wrongquestionset.room.entity.QuestionSetEntity
import com.sunshine.wrongquestionset.room.entity.SubjectEntity
import kotlinx.android.synthetic.main.fragment_search.*
import kotlin.reflect.KFunction1


/**
 * 搜索页
 */
class SearchFragment : Fragment() {

    private lateinit var viewModel: MainViewModel

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_search, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        viewModel = ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory.getInstance(requireActivity().application)).get(MainViewModel::class.java)

        initSearchBar()
    }

    /**
     * 初始化搜索框
     */
    private fun initSearchBar() {

        var subjectList: List<SubjectEntity>? = null
        var questionSetList: List<QuestionSetEntity>? = null
        var questionList: List<QuestionEntity>? = null

        (requireActivity() as MainActivity).getLoginUserId(object : OnRefreshListener<String>() {
            /**
             * @param obj userId
             */
            override fun onUpdate(obj: String) {
                super.onUpdate(obj)

                viewModel.getSubject(obj).observe(viewLifecycleOwner, Observer {
                    subjectList = it
                })

                viewModel.getQuestionSet(obj).observe(viewLifecycleOwner, Observer {
                    questionSetList = it
                })

                viewModel.getQuestion(obj).observe(viewLifecycleOwner, Observer {
                    questionList = it
                })
            }
        })

        searchView.apply {
            isSubmitButtonEnabled = true

            //去掉搜索框默认的下划线
            val searchPlate: LinearLayout = findViewById(R.id.search_plate)
            val submitArea: LinearLayout = findViewById(R.id.submit_area)
            searchPlate.background = null
            submitArea.background = null

            val recyclerAdapter = SearchRecyclerAdapter(viewLifecycleOwner, viewModel, requireActivity() as AppCompatActivity)

            recyclerView.setLayoutManager(LinearLayoutManager(requireContext()))
            recyclerView.setAdapter(recyclerAdapter)

            setOnQueryTextListener(object : SearchView.OnQueryTextListener {
                override fun onQueryTextSubmit(query: String?): Boolean {

                    return true
                }

                override fun onQueryTextChange(newText: String?): Boolean {
                    val queryList = ArrayList<SearchBean>()
                    if (newText.isNullOrBlank()) {
                        recyclerAdapter.setFilter(queryList)
                        return true
                    }
                    subjectList?.filter(newText, queryList, SearchBean.TYPE_SUBJECT)
                    questionSetList?.filter(newText, queryList, SearchBean.TYPE_QUESTION_SET)
                    questionList?.filter(newText, queryList, SearchBean.TYPE_QUESTION)

                    recyclerAdapter.setFilter(queryList)

                    return true
                }

            })
        }
    }

    /**
     * 对列表进行筛选
     * kotlin扩展函数
     */
    private fun <T> List<T>.filter(
        query: String,
        queryList: ArrayList<SearchBean>,
        type: Int
        ) {
        when (type) {
            1 -> {
                forEach {
                    val entity = (it as SubjectEntity)
                    if(entity.name.contains(query, true)) {
                        queryList.add(SearchBean(entity.id, SearchBean.TYPE_SUBJECT, entity.name, null, -1))
                    }
                }
            }
            2 -> {
                forEach {
                    val entity = (it as QuestionSetEntity)
                    if(entity.name.contains(query, true)) {
                        queryList.add(SearchBean(entity.id, SearchBean.TYPE_QUESTION_SET, entity.name, it.description, entity.subjectId))
                    }
                }
            }
            3 -> {
                forEach {
                    val entity = (it as QuestionEntity)
                    if (entity.tag.contains(query, true) || entity.titlePath.contains(query, true) || entity.answerPath.contains(query, true)) {
                        queryList.add(SearchBean(entity.id, SearchBean.TYPE_QUESTION, entity.titlePath, entity.tag, -1))
                    }
                }
            }
        }
    }
}